﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
using Fcdbas.Core;
using Fcdbas.WinUI.Common;

namespace Fcdbas.Biz
{
    
    internal class WhereValue{
        public WhereValue(string field, object val, string oper,bool ucase)
        {
            Field = field;
            Value = val;
            Oper = oper;
            UCase = ucase;
        }
        public string Field{get;set;}
        public object Value{get;set;}
        public string Oper { get; set; }
        public bool UCase { get; set; }
    }
    internal sealed class FndObjectFactory
    {
        internal static fnd_pres_object CreatePreObject(Type t, string lu_name_, string module_, string desc_)
        {
            fnd_pres_object preObject = new fnd_pres_object();
            preObject.pres_object = t.FullName;
            preObject.module = module_;
            preObject.lu_name = lu_name_;
            preObject.object_type = SecObjectType.Window;
            preObject.description = desc_;
            return preObject;
        }
        internal static fnd_object_security CreateObjectSecurity(Type t,string secObject_,string secObjectType_,string subObjectType_,string desc_,string forceRd)
        {
            //fnd_object_security secObject = new fnd_object_security();
            //secObject.pres_object = t.FullName;
            //secObject.sec_object = secObject_;
            //secObject.sec_object_type = secObjectType_;
            //secObject.sub_object_type = subObjectType_;
            //secObject.description = desc_;
            //secObject.force_read_only = forceRd;
            return CreateObjectSecurity(t.FullName, secObject_, secObjectType_, subObjectType_, desc_, forceRd);
        }
        internal static fnd_object_security CreateObjectSecurity(string pres_object, string secObject_, string secObjectType_, string subObjectType_, string desc_, string forceRd)
        {
            fnd_object_security secObject = new fnd_object_security();
            secObject.pres_object = pres_object;
            secObject.sec_object = secObject_;
            secObject.sec_object_type = secObjectType_;
            secObject.sub_object_type = subObjectType_;
            secObject.description = desc_;
            secObject.force_read_only = forceRd;
            return secObject;
        }
    }
    public sealed class FndDAL
    {
        public static readonly string SQLite = "SQLite";
        private static List<fnd_pres_object> PresObjects = null;
        private static List<fnd_object_security> ObjectSecuritys = null;
        public static void InitFndDataSource()
        {
            if (!AppEnvironment.Session.IsRoot)
                return;
            AddDSSecurity(typeof(Fcdbas.WinUI.Forms.frmMainForm), "fnd_exp_navigator", SecObjectType.View, "*", "False");
            AddDSSecurity(typeof(Fcdbas.WinUI.Forms.frmMainForm), "fnd_language_sys", SecObjectType.View, "*", "False");
            AddDSSecurity(typeof(Fcdbas.WinUI.Forms.frmMainForm), "fnd_language_code", SecObjectType.View, "*", "False");
            AddDSSecurity(typeof(Fcdbas.WinUI.Forms.frmMainForm), "fnd_object_security", SecObjectType.View, "*", "False");
            AddDSSecurity(typeof(Fcdbas.WinUI.Forms.frmMainForm), "fnd_pres_object", SecObjectType.View, "*", "False");
            AddDSSecurity(typeof(Fcdbas.WinUI.Forms.frmMainForm), "fnd_user_security", SecObjectType.View, "*", "False");
            AddDSSecurity(typeof(Fcdbas.WinUI.Forms.frmMainForm), "fnd_user_profile", SecObjectType.View, "*", "False");
            AddDSSecurity(typeof(Fcdbas.WinUI.Forms.frmMainForm), "approval_profile", SecObjectType.View, "*", "False");
            AddDSSecurity(typeof(Fcdbas.WinUI.Forms.frmMainForm), "approval_routing", SecObjectType.View, "*", "False");
            AddDSSecurity(typeof(Fcdbas.WinUI.Forms.frmMainForm), "person_group", SecObjectType.View, "*", "False");
            AddDSSecurity(typeof(Fcdbas.WinUI.Forms.frmMainForm), "person_info", SecObjectType.View, "*", "False");
            AddDSSecurity(typeof(Fcdbas.WinUI.Forms.frmMainForm), "FndUserProfile_New", SecObjectType.Procedure, "新增", "False");
            AddDSSecurity(typeof(Fcdbas.WinUI.Forms.frmMainForm), "FndUserProfile_Modify", SecObjectType.Procedure, "修改", "False");
            AddDSSecurity(typeof(Fcdbas.WinUI.Forms.frmMainForm), "SecuritySys_NewPresObject", SecObjectType.Procedure, "新增", "False");
            AddDSSecurity(typeof(Fcdbas.WinUI.Forms.frmMainForm), "SecuritySys_NewPresSecurity", SecObjectType.Procedure, "新增", "False");
            AddDSSecurity(typeof(Fcdbas.WinUI.Forms.frmMainForm), "FndLanguageSys_NewContext", SecObjectType.Procedure, "新增", "False");

            AddDSSecurity(typeof(Fcdbas.WinUI.Forms.frmMainForm), "ApprovalRouting_CreateRouting", SecObjectType.Procedure, "新增", "False");
            AddDSSecurity(typeof(Fcdbas.WinUI.Forms.frmMainForm), "ApprovalRouting_RemoveStep", SecObjectType.Procedure, "删除步骤", "False");
            AddDSSecurity(typeof(Fcdbas.WinUI.Forms.frmMainForm), "ApprovalRouting_Modify__", SecObjectType.Procedure, "修改", "False");
            AddDSSecurity(typeof(Fcdbas.WinUI.Forms.frmMainForm), "ApprovalRouting_DoApproval", SecObjectType.Procedure, "审核", "False");
            AddDSSecurity(typeof(Fcdbas.WinUI.Forms.frmMainForm), "ApprovalRouting_DoReject", SecObjectType.Procedure, "拒绝", "False");
            AddDSSecurity(typeof(Fcdbas.WinUI.Forms.frmMainForm), "ApprovalRouting_DoRevise", SecObjectType.Procedure, "取消", "False");
            //AddDSSecurity(typeof(Fcdbas.WinUI.Forms.frmMainForm), "FndLanguageSys_NewContext", SecObjectType.Procedure, "新增", "False");
           // AddDSSecurity(typeof(Fcdbas.WinUI.Forms.frmMainForm), "SecuritySys_NewPresObject", SecObjectType.Procedure, "新增", "False");
        }
        // <summary>  
        /// 读取Excel文件到DataSet中  
        /// </summary>  
        /// <param name="filePath">文件路径</param>  
        /// <returns></returns>  
        public static DataSet ToDataTable(string filePath)
        {
            string connStr = "";
            string fileType = System.IO.Path.GetExtension(filePath);
            if (string.IsNullOrEmpty(fileType)) return null;

            if (fileType == ".xls")
                connStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filePath + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
            else
                connStr = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + filePath + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
            string sql_F = "Select * FROM [{0}]";

            OleDbConnection conn = null;
            OleDbDataAdapter da = null;
            DataTable dtSheetName = null;

            DataSet ds = new DataSet();
            try
            {
                // 初始化连接，并打开  
                conn = new OleDbConnection(connStr);
                conn.Open();

                // 获取数据源的表定义元数据                         
                string SheetName = "";
                dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });

                // 初始化适配器  
                da = new OleDbDataAdapter();
                for (int i = 0; i < dtSheetName.Rows.Count; i++)
                {
                    SheetName = (string)dtSheetName.Rows[i]["TABLE_NAME"];

                    if (SheetName.Contains("$") && !SheetName.Replace("'", "").EndsWith("$"))
                    {
                        continue;
                    }

                    da.SelectCommand = new OleDbCommand(String.Format(sql_F, SheetName), conn);
                    DataSet dsItem = new DataSet();
                    da.Fill(dsItem, SheetName);

                    ds.Tables.Add(dsItem.Tables[0].Copy());
                }
            }
            catch (Exception ex)
            {
                Fcdbas.Core.Log.XTrace.WriteException(ex);
            }
            finally
            {
                // 关闭连接  
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                    da.Dispose();
                    conn.Dispose();
                }
            }
            return ds;
        }
        public static List<string> GetExcelSheet(string filePath)
        {
            string connStr = "";
            string fileType = System.IO.Path.GetExtension(filePath);
            if (string.IsNullOrEmpty(fileType)) return null;

            if (fileType == ".xls")
                connStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filePath + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
            else
                connStr = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + filePath + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
           

            OleDbConnection conn = null;
         //   OleDbDataAdapter da = null;
            DataTable dtSheetName = null;

            List<string> list = new List<string>();
            try
            {
                // 初始化连接，并打开  
                conn = new OleDbConnection(connStr);
                conn.Open();

                // 获取数据源的表定义元数据                         
                string SheetName = "";
                dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });

                for (int i = 0; i < dtSheetName.Rows.Count; i++)
                {
                    SheetName = (string)dtSheetName.Rows[i]["TABLE_NAME"];

                    if (SheetName.Contains("$") && !SheetName.Replace("'", "").EndsWith("$"))
                    {
                        continue;
                    }

                    list.Add(SheetName);
                }
            }
            catch (Exception ex)
            {
                Fcdbas.Core.Log.XTrace.WriteException(ex);
                WinTranslate.GetTranslate().ShowMessage(ex.Message);
            }
            finally
            {
                // 关闭连接  
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                   
                    conn.Dispose();
                }
            }
            return list;
        }
        // <summary>  
        /// 读取Excel文件中指定的Sheet到DataSet中  
        /// </summary>  
        /// <param name="filePath">文件路径</param>  
        /// <returns></returns>  
        public static DataSet ToDataTable(string filePath,string sheetName)
        {
            string connStr = "";
            string fileType = System.IO.Path.GetExtension(filePath);
            if (string.IsNullOrEmpty(fileType)) return null;

            if (fileType == ".xls")
                connStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filePath + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
            else
                connStr = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + filePath + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
            string sql_F = "Select * FROM [{0}]";
            sql_F = string.Format(sql_F, sheetName);
            OleDbConnection conn = null;
            OleDbDataAdapter da = null;
          //  DataTable dtSheetName = null;

            DataSet ds = new DataSet();
            try
            {
                // 初始化连接，并打开  
                conn = new OleDbConnection(connStr);
                conn.Open();

                
                // 初始化适配器  
                da = new OleDbDataAdapter();


                da.SelectCommand = new OleDbCommand(sql_F, conn);
                   // DataSet dsItem = new DataSet();
                da.Fill(ds, sheetName);
            }
            catch (Exception ex)
            {
                Fcdbas.Core.Log.XTrace.WriteException(ex);
                WinTranslate.GetTranslate().ShowMessage(ex.Message);
            }
            finally
            {
                // 关闭连接  
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                    da.Dispose();
                    conn.Dispose();
                }
            }
            return ds;
        } 
        /// <summary>
        /// 查找用户配置
        /// </summary>
        /// <param name="identify"></param>
        /// <param name="pres_object"></param>
        /// <param name="type_flag">Profile类型,U:用户， W: Window; Q: Query; E: Exploer; D: Design</param>
        /// <returns></returns>
        public static fnd_user_profile FindUserProfile(string identify, string pres_object, string type_flag)
        {
            if (!Fcdbas.WinUI.Common.Security.IsViewAvaliable(Fcdbas.WinUI.Common.AppEnvironment.Session.USER_ID, "fnd_user_profile"))
            {
                Fcdbas.WinUI.Common.WinTranslate.GetTranslate().ShowMessage("没有查询视图[%%1]的权限，请联系系统管理员。", "fnd_user_profile");
                return null;
            }
            string where = BuildCondition(new WhereValue("identity", identify, "=", true), new WhereValue("pres_object", pres_object, "=", true), new WhereValue("type_flag", type_flag, "=", true));
            string conName = fnd_user_profile.Meta.ConnName;
            fnd_user_profile.Meta.ConnName = SQLite;
            List<fnd_user_profile> list= fnd_user_profile.FindAll(where, "", "", 0, 0);
            fnd_user_profile.Meta.ConnName = conName;
            if (list == null || list.Count == 0)
            {
                return null;
            }
            else
            {
                return list[0];
            }
        }
        /// <summary>
        /// 查找用户配置
        /// </summary>
        /// <param name="identify"></param>
        /// <param name="pres_object"></param>
        /// <param name="type_flag">Profile类型,U:用户， W: Window; Q: Query; E: Exploer; D: Design</param>
        /// <returns></returns>
        public static List<fnd_user_profile> FindUserProfiles(string identify, string pres_object, string type_flag)
        {
            if (!Fcdbas.WinUI.Common.Security.IsViewAvaliable(Fcdbas.WinUI.Common.AppEnvironment.Session.USER_ID, "fnd_user_profile"))
            {
                Fcdbas.WinUI.Common.WinTranslate.GetTranslate().ShowMessage("没有查询号视图[%%1]的权限，请联系系统管理员。", "fnd_user_profile");
                return null;
            }
            string where = BuildCondition(new WhereValue("identity", identify, "=", true), new WhereValue("pres_object", pres_object, "=", true), new WhereValue("type_flag", type_flag, "=", true));
            string conName = fnd_user_profile.Meta.ConnName;
            fnd_user_profile.Meta.ConnName = SQLite;
            List<fnd_user_profile> list = fnd_user_profile.FindAll(where, "", "", 0, 0);
            fnd_user_profile.Meta.ConnName = conName;
            return list;
        }
        internal static string BuildCondition( params WhereValue[] list)
        {
            string where = "";
            foreach (WhereValue wv in list)
            {
                if (wv.Value == null || string.IsNullOrEmpty(wv.Value.ToString()))
                    continue;
                if (wv.Value.GetType() == typeof(string))
                {
                    switch (wv.Oper)
                    {
                        case "=":

                            if (!wv.UCase)
                                where += string.IsNullOrEmpty(where) ? "ucase(" + wv.Field + ")=ucase('" + wv.Value.ToString() + "')" : "and ucase(" + wv.Field + ")=ucase('" + wv.Value.ToString() + "')";
                            else
                                where += string.IsNullOrEmpty(where) ? wv.Field + " ='" + wv.Value.ToString() + "'" : (" and " + wv.Field + " ='" + wv.Value.ToString() + "'");
                            break;
                        case "%":
                            where += string.IsNullOrEmpty(where) ?  wv.Field + " LIKE '" + wv.Value.ToString() + "%'" : (" and " + wv.Field + " LIKE '" + wv.Value.ToString() + "%'");
                             break;
                        case "!":
                            where +=  string.IsNullOrEmpty(where) ?  wv.Field + " IS NULL" : (" and " + wv.Field + " IS NULL");
                             break;
                        case ">":
                            where +=  string.IsNullOrEmpty(where) ?  wv.Field + " >'" + wv.Value.ToString() + "'" : (" and " + wv.Field + " >'" + wv.Value.ToString() + "'");
                             break;
                        case "<":
                            where +=  string.IsNullOrEmpty(where) ?  wv.Field + " <'" + wv.Value.ToString() + "'" : (" and " + wv.Field + " <'" + wv.Value.ToString() + "'");
                             break;
                        case ">=":
                            where +=  string.IsNullOrEmpty(where) ?  wv.Field + " >='" + wv.Value.ToString() + "'" : (" and " + wv.Field + " >='" + wv.Value.ToString() + "'");
                             break;
                        case "<=":
                            where +=  string.IsNullOrEmpty(where) ?  wv.Field + " <='" + wv.Value.ToString() + "'" : (" and " + wv.Field + " <='" + wv.Value.ToString() + "'");
                             break;
                        case "!=":
                            where +=  string.IsNullOrEmpty(where) ?  wv.Field + " !='" + wv.Value.ToString() + "'" : (" and " + wv.Field + " !='" + wv.Value.ToString() + "'");
                             break;
                        case "..":
                            {
                                string[] s1 = wv.Value.ToString().Split("..");
                                if (s1.Length >= 2)
                                {
                                    where +=  string.IsNullOrEmpty(where) ?  wv.Field + " BETWEEN '" + s1[0] + "' AND '" + s1[1] + "'" : (" and " +  wv.Field + " BETWEEN '" + s1[0] + "' AND '" + s1[1] + "'");
                                }
                                else
                                    return "ERROR";
                                break;
                            }
                        case ";":
                            {
                                string[] s2 = wv.Value.ToString().Split(";");
                                string where1 = wv.Field + " IN ('";
                                foreach (string s in s2)
                                {
                                    where1 += s + "',";
                                }
                                where1 = where1.Remove(where1.Length - 1);
                                where1 += ")";
                                where += string.IsNullOrEmpty(where) ? where1 : (" and " + where1);
                                 break;
                            }
                    }

                }
                if (wv.Value.GetType() == typeof(decimal) || wv.Value.GetType() == typeof(int) || wv.Value.GetType() == typeof(float))
                {
                    switch (wv.Oper)
                    {
                        case "=":

                            where +=  string.IsNullOrEmpty(where) ?  wv.Field + " =" + wv.Value.ToString() + "" : (" and " +  wv.Field + " =" + wv.Value.ToString() + "");
                             break;
                        case "%":
                            where +=  string.IsNullOrEmpty(where) ?  wv.Field + " LIKE '" + wv.Value.ToString() + "%'" : (" and " + wv.Field + " LIKE '" + wv.Value.ToString() + "%'");
                             break;
                        case "!":
                            where +=  string.IsNullOrEmpty(where) ?  wv.Field + " IS NULL" : (" and " + wv.Field + " IS NULL");
                             break;
                        case ">":
                            where +=  string.IsNullOrEmpty(where) ?  wv.Field + " >" + wv.Value.ToString() : (" and " + wv.Field + " >" + wv.Value.ToString());
                             break;
                        case "<":
                            where +=  string.IsNullOrEmpty(where) ?  wv.Field + " <" + wv.Value.ToString() : (" and " + wv.Field + " <" + wv.Value.ToString());
                             break;
                        case ">=":
                            where +=  string.IsNullOrEmpty(where) ?  wv.Field + " >=" + wv.Value.ToString() : (" and " + wv.Field + " >=" + wv.Value.ToString());
                             break;
                        case "<=":
                            where +=  string.IsNullOrEmpty(where) ?  wv.Field + " <=" + wv.Value.ToString() : (" and " + wv.Field + " <=" + wv.Value.ToString());
                             break;
                        case "!=":
                            where +=  string.IsNullOrEmpty(where) ?  wv.Field + " !=" + wv.Value.ToString() : (" and " + wv.Field + " !=" + wv.Value.ToString());
                             break;
                        case "..":
                            {
                                string[] s1 = wv.Value.ToString().Split("..");
                                if (s1.Length >= 2)
                                {
                                    where +=  string.IsNullOrEmpty(where) ?  wv.Field + " BETWEEN " + s1[0] + " AND " + s1[1] : (" and " + wv.Field + " BETWEEN " + s1[0] + " AND " + s1[1]);
                                }
                                else
                                    return "ERROR";
                                 break;
                            }
                        case ";":
                            {
                                string[] s2 = wv.Value.ToString().Split(";");
                                string where2 = wv.Field + " IN (";
                                foreach (string s in s2)
                                {
                                    where2 += s + ",";
                                }
                                where2 = where.Remove(where2.Length - 1);
                                where2 += ")";
                                where += string.IsNullOrEmpty(where) ? where2 : (" and " + where2);
                                 break;
                            }
                    }

                }
                if (wv.Value.GetType() == typeof(DateTime))
                {
                    string sdate = "", format = "";
                    switch (wv.Oper)
                    {
                        case "=":
                            if (!ConverToStandard(wv.Value.ToString(), ref sdate, ref format))
                                return "ERROR";
                            where +=  string.IsNullOrEmpty(where) ?  wv.Field + " = str_to_date('" + sdate + "'," + format + ")" : (" and " + wv.Field + " = str_to_date('" + sdate + "'," + format + ")");
                             break;
                        case "%":
                            where +=  string.IsNullOrEmpty(where) ?  wv.Field + " LIKE '" + wv.Value.ToString() + "%'" : (" and " + wv.Field + " LIKE '" + wv.Value.ToString() + "%'");
                             break;
                        case "!":
                            where +=  string.IsNullOrEmpty(where) ?  wv.Field + " IS NULL" : (" and " + wv.Field + " IS NULL");
                             break;
                        case ">":
                            if (!ConverToStandard(wv.Value.ToString(), ref sdate, ref format))
                                return "ERROR";
                            where +=  string.IsNullOrEmpty(where) ?  wv.Field + " > str_to_date('" + sdate + "'," + format + ")" : (" and " + wv.Field + " > str_to_date('" + sdate + "'," + format + ")");
                            break;
                        case "<":
                            if (!ConverToStandard(wv.Value.ToString(), ref sdate, ref format))
                                return "ERROR";
                            where +=  string.IsNullOrEmpty(where) ?  wv.Field + " < str_to_date('" + sdate + "'," + format + ")" : (" and " + wv.Field + " < str_to_date('" + sdate + "'," + format + ")");
                            break;
                        case ">=":
                            if (!ConverToStandard(wv.Value.ToString(), ref sdate, ref format))
                                return "ERROR";
                            where +=  string.IsNullOrEmpty(where) ?  wv.Field + " >= str_to_date('" + sdate + "'," + format + ")" : (" and " + wv.Field + " >= str_to_date('" + sdate + "'," + format + ")");
                            break;
                        case "<=":
                            if (!ConverToStandard(wv.Value.ToString(), ref sdate, ref format))
                                return "ERROR";
                            where +=  string.IsNullOrEmpty(where) ?  wv.Field + " <= str_to_date('" + sdate + "'," + format + ")" : (" and " + wv.Field + " <= str_to_date('" + sdate + "'," + format + ")");
                            break;
                        case "!=":
                            if (!ConverToStandard(wv.Value.ToString(), ref sdate, ref format))
                                return "ERROR";
                            where +=  string.IsNullOrEmpty(where) ?  wv.Field + " != str_to_date('" + sdate + "'," + format + ")" : (" and " + wv.Field + " != str_to_date('" + sdate + "'," + format + ")");
                            break;
                        case "..":
                            {
                                string[] s1 = wv.Value.ToString().Split("..");
                                string ss2 = "", format2 = "";
                                if (s1.Length >= 2)
                                {
                                    if (!ConverToStandard(s1[0], ref sdate, ref format))
                                        return "ERROR";
                                    if (!ConverToStandard(s1[1], ref ss2, ref format2))
                                        return "ERROR";

                                    where +=  string.IsNullOrEmpty(where) ?  wv.Field + " BETWEEN str_to_date('" + sdate + "'," + format + ")" + " AND " + "str_to_date('" + ss2 + "'," + format2 + ")" : (" and " + wv.Field + " BETWEEN str_to_date('" + sdate + "'," + format + ")" + " AND " + "str_to_date('" + ss2 + "'," + format2 + ")");
                                }
                                else
                                    return "ERROR";
                                break;
                            }
                        case ";":
                            {
                                string[] s2 = wv.Value.ToString().Split(";");
                                string where3 = wv.Field + " IN (";
                                foreach (string s in s2)
                                {
                                    where3 += s + ",";
                                }
                                where3 = where.Remove(where3.Length - 1);
                                where3 += ")";
                                where += string.IsNullOrEmpty(where) ? where3 : (" and " + where3) ;
                                break;
                            }
                    }

                }
            }
            return where;
        }
        private static bool ConverToStandard(string date, ref string ldate, ref string format)
        {
            string sdate = date.Trim();
            string[] s1 = sdate.Split(" ");
            string d = "", t = "";
            if (s1.Length >= 2)
            {
                d = s1[0];
                t = s1[1];
            }
            else
            {
                d = sdate;
            }
            if (!string.IsNullOrEmpty(d))
            {
                string[] s2 = d.Split('-');
                if (s2.Length != 3)
                    return false;
                d = s2[0] + "-";
                d = d + (s2[1].Length == 1 ? s2[1].PadLeft(2, '0') : s2[1]);
                d += "-";
                d = d + (s2[2].Length == 1 ? s2[2].PadLeft(2, '0') : s2[2]);
            }
            if (!string.IsNullOrEmpty(t))
            {
                string[] s2 = t.Split(':');
                if (s2.Length > 3)
                    return false;
                else
                    t = t + ":00:00";
                if (s2.Length == 1)
                    t = s2[0] + ":00:00";
                if (s2.Length == 2)
                    t = s2[0] + ":" + s2[1] + ":00";
                if (s2.Length == 3)
                    t = s2[0] + ":" + s2[1] + ":" + s2[2];
            }
            if (string.IsNullOrEmpty(t))
            {
                ldate = d;
                format = "'%Y-%m-%d'";
            }
            else
            {
                ldate = d + " " + t;
                format = "'%Y-%m-%d %H:%i:%s'";
            }
            return true;
        }
        /// <summary>
        /// 新建
        /// </summary>
        /// <param name="upfile"></param>
        /// <returns></returns>
        public static SalBoolean UserProfileNew(fnd_user_profile upfile,bool IsOnlyLocal = false)
        {
            if (!IsOnlyLocal && !cSessionManager.IsRemote)
                cSessionManager.DbTransactionBegin();
            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("objid_", "");
            dic.Add("identity_", upfile.identity);
            dic.Add("pres_object_", upfile.pres_object);
            dic.Add("type_flag_", upfile.type_flag);
            dic.Add("description_", upfile.description);
            dic.Add("info_", upfile.info);
            dic.Add("where_clause_", upfile.where_clause);
            dic.Add("order_clause_", upfile.order_clause);
            dic.Add("data_source_", upfile.data_source);
            dic.Add("note_text_", upfile.note_text);
            SalBoolean res = true;
            if (!IsOnlyLocal)
            {
                if (cSessionManager.IsRemote)
                {
                    cSessionManager.RemoteSQLExecute("FndUserProfile_New(:objid_,:identity_,:pres_object_,:type_flag_,:description_,:info_,:where_clause_,:order_clause_,:data_source_,:note_text_)", dic);
                }
                else
                    cSessionManager.DbMySQLBlock("FndUserProfile_New(:objid_,:identity_,:pres_object_,:type_flag_,:description_,:info_,:where_clause_,:order_clause_,:data_source_,:note_text_)", dic);
            }
            if (res)
            {
                upfile.Status = RecordStatus.Normal;
                if (!IsOnlyLocal)
                    cSessionManager.DbTransactionEnd();
                //string objid = dic["objid_"].ToString();
                //fnd_user_profile upf = fnd_user_profile.Find("rowid", objid);
                //if (upf == null)
                //    return false;
                string conName = fnd_user_profile.Meta.ConnName;
                fnd_user_profile.Meta.ConnName = SQLite;
                upfile.Insert();
               // upfile.BeginTrans();
                //if (upfile.Insert() > 0)
                //    upfile.Commit();
                //else
                //    upfile.Rollback();
                fnd_user_profile.Meta.ConnName = conName;
            }
            else
            {
                if (!IsOnlyLocal)
                {
                    if(!cSessionManager.IsRemote)
                        cSessionManager.DbTransactionClear();
                    SalString sRes = "";
                    cSessionManager.GetSqlLastError(ref sRes);
                    WinTranslate.GetTranslate().ShowMessage(sRes, "", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                }
            }
            return res;
        }
        public static SalBoolean FndBinaryObjectNew(fnd_binary_object entity, SalBoolean bTranslaction)
        {

            SalString sSql = "FndBinaryObject_NewObject(:blob_id_,:file_path_,:file_name_,:display_text_,:data_,:binary_object_type_)";
            if (bTranslaction)
                cSessionManager.DbTransactionBegin();
             Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("blob_id_", "0");
            dic.Add("file_path_", entity.file_path);
            dic.Add("file_name_", entity.file_name);
            dic.Add("display_text_", entity.display_text);
            dic.Add("data_", entity.data);
            dic.Add("binary_object_type_", entity.binary_object_type);
            SalBoolean res = true;
            if (cSessionManager.IsRemote)
            {
                res = cSessionManager.RemoteSQLExecute(sSql, dic);
            }
            else
                res = cSessionManager.DbMySQLBlock(sSql, dic, System.Data.CommandType.StoredProcedure);
            if (res && bTranslaction && !cSessionManager.IsRemote)
                cSessionManager.DbTransactionEnd();
            else
            {
                if(bTranslaction && !cSessionManager.IsRemote)
                    cSessionManager.DbTransactionClear();
                if (!res)
                {
                    SalString msg = "";
                    cSessionManager.GetSqlLastError(ref msg);
                    WinTranslate.GetTranslate().ShowMessage(msg, "", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                }
            }
            entity.blob_id = Convert.ToInt32(dic["blob_id_"].ToString());
            return res;
        }
        public static SalBoolean FndBinaryObjectModify(fnd_binary_object entity, SalBoolean bTranslaction)
        {

            SalString sSql = "FndBinaryObject_ModifyObject(:blob_id_,:file_path_,:file_name_,:display_text_,:data_)";
            if (bTranslaction && !cSessionManager.IsRemote)
                cSessionManager.DbTransactionBegin();
            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("blob_id_", entity.blob_id);
            dic.Add("file_path_", entity.file_path);
            dic.Add("file_name_", entity.file_name);
            dic.Add("display_text_", entity.display_text);
            dic.Add("data_", entity.data);
            SalBoolean res = true;
            if (cSessionManager.IsRemote)
                res = cSessionManager.RemoteSQLExecute(sSql, dic);
            else
                res=  cSessionManager.DbMySQLBlock(sSql, dic, System.Data.CommandType.StoredProcedure);
            if (res && bTranslaction)
                cSessionManager.DbTransactionEnd();
            else
            {
                if (bTranslaction && !cSessionManager.IsRemote)
                    cSessionManager.DbTransactionClear();
                if (!res)
                {
                    SalString msg = "";
                    cSessionManager.GetSqlLastError(ref msg);
                    WinTranslate.GetTranslate().ShowMessage(msg, "", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                }
            }
            return res;
        }
        public static SalBoolean FndBinaryObjectRemove(SalNumber blob_id, SalBoolean bTranslaction)
        {

            SalString sSql = "FndBinaryObject_RemoveObject(:blob_id_)";
            if (bTranslaction && !cSessionManager.IsRemote)
                cSessionManager.DbTransactionBegin();
            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("blob_id_", blob_id);

            SalBoolean res = true;
            if (cSessionManager.IsRemote)
                res = cSessionManager.RemoteSQLExecute(sSql, dic);
            else
                res = cSessionManager.DbMySQLBlock(sSql, dic, System.Data.CommandType.StoredProcedure);
            if (res && bTranslaction && !cSessionManager.IsRemote)
                cSessionManager.DbTransactionEnd();
            else
            {
                if (bTranslaction && cSessionManager.IsRemote)
                    cSessionManager.DbTransactionClear();
                if (!res)
                {
                    SalString msg = "";
                    cSessionManager.GetSqlLastError(ref msg);
                    WinTranslate.GetTranslate().ShowMessage(msg, "", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                }
            }
            return res;
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="upfile"></param>
        /// <returns></returns>
        public static SalBoolean UserProfileModify(fnd_user_profile upfile,bool IsOnlyLocal=false)
        {
            if (!IsOnlyLocal && !cSessionManager.IsRemote)
                cSessionManager.DbTransactionBegin();
            SalString sSql = "FndUserProfile_Modify(:identity_,:pres_object_,:type_flag_,:item_seq_no_,:info_,:description_,:where_clause_,:order_clause_,:data_source_,:note_text_)";
            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("identity_", upfile.identity);
            dic.Add("pres_object_", upfile.pres_object);
            dic.Add("type_flag_", upfile.type_flag);
            dic.Add("item_seq_no_", upfile.item_seq_no);
            dic.Add("info_", upfile.info);
            dic.Add("description_", upfile.description);
            dic.Add("where_clause_", upfile.where_clause);
            dic.Add("order_clause_", upfile.order_clause);
            dic.Add("data_source_", upfile.data_source);
            dic.Add("note_text_", upfile.note_text);
            SalBoolean res = true;
            if (!IsOnlyLocal)
            {
                if (cSessionManager.IsRemote)
                    res = cSessionManager.RemoteSQLExecute(sSql, dic);
                else
                    res = cSessionManager.DbMySQLBlock(sSql, dic);
            }
            if (res)
            {
                upfile.Status = RecordStatus.Normal;
                if (!IsOnlyLocal && !cSessionManager.IsRemote )
                    cSessionManager.DbTransactionEnd();
                string conName = fnd_user_profile.Meta.ConnName;
                fnd_user_profile.Meta.ConnName = SQLite;
                upfile.Update();
                fnd_user_profile.Meta.ConnName = conName;
                //upfile.BeginTrans();
                //if (upfile.Update() > 0)
                //    upfile.Commit();
                //else
                //    upfile.Rollback();
            }
            else
            {
                if (!IsOnlyLocal)
                {
                    if(!cSessionManager.IsRemote)
                        cSessionManager.DbTransactionClear();
                    SalString sRes = "";
                    cSessionManager.GetSqlLastError(ref sRes);
                    WinTranslate.GetTranslate().ShowMessage(sRes, "", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                }
            }
            return res;
        }
        public static fnd_pres_object FindPresObject(string presObject)
        {
            if (presObject == null)
                return null;
            if (PresObjects == null)
            {
                if (!Fcdbas.WinUI.Common.Security.IsViewAvaliable(Fcdbas.WinUI.Common.AppEnvironment.Session.USER_ID, "fnd_pres_object"))
                {
                    Fcdbas.WinUI.Common.WinTranslate.GetTranslate().ShowMessage("没有查询视图[%%1]的权限，请联系系统管理员。", "fnd_pres_object");
                    return null;
                }
                PresObjects = fnd_pres_object.FindAll();
            }
            return PresObjects.Find(p => p.pres_object == presObject);
        }
        public static SalBoolean PresObjectNew(fnd_pres_object pobject,bool IsLocal )
        {
            if(pobject == null)
                return false;
            if (IsLocal)
            {
                string conName = fnd_pres_object.Meta.ConnName;
                fnd_pres_object.Meta.ConnName = FndDAL.SQLite;
                string where = "pres_object = '" + pobject.pres_object +  "'";
                int suc = 0;
                if (fnd_pres_object.Find(where) != null)
                    suc = pobject.Update();
                else
                    suc = pobject.Insert();
                

                fnd_pres_object.Meta.ConnName = conName;
                if (suc == 1)
                    return true;
                else
                    return false;
            }
            else
            {
                SalBoolean res =true;
                SalString sSql = "SecuritySys_NewPresObject(:pres_object_ , :description_,:object_type_,:module_ ,:lu_name_)";
                if (cSessionManager.IsRemote)
                {
                    res = cSessionManager.RemoteSQLExecute(pobject, sSql);
                    if(res)
                        PresObjects.Add(pobject);
                }
                else
                {
                    cSessionManager session = new cSessionManager(null);
                    session.DbTransactionBegin(pobject);
                    
                    res = session.DbSQLBlock(pobject, sSql, false);
                
                    if (res)
                    {
                        session.DbTransactionEnd(pobject);
                        PresObjects.Add(pobject);
                    }
                    else
                        session.DbTransactionClear(pobject);
                }
                return res;
            }
        }
        public static fnd_object_security FindObjectSecurity(fnd_object_security objSec)
        {
            if (objSec == null)
                return null;
            if (ObjectSecuritys == null)
            {
                if (!Fcdbas.WinUI.Common.Security.IsViewAvaliable(Fcdbas.WinUI.Common.AppEnvironment.Session.USER_ID, "fnd_object_security"))
                {
                    Fcdbas.WinUI.Common.WinTranslate.GetTranslate().ShowMessage("没有查询视图[%%1]的权限，请联系系统管理员。", "fnd_object_security");
                    return null;
                }
                ObjectSecuritys = fnd_object_security.FindAll();
            }
            return ObjectSecuritys.Find(p => p.pres_object == objSec.pres_object && p.sec_object == objSec.sec_object && p.sec_object_type == objSec.sec_object_type && p.sub_object_type == objSec.sub_object_type);

        }

        public static SalBoolean ObjectSecurityNew(fnd_object_security objSec,bool IsLocal  =true)
        {
            //先关掉
            //return true;
            if (objSec == null)
                return false;
            if (IsLocal)
            {
                string conName = fnd_object_security.Meta.ConnName;
                fnd_object_security.Meta.ConnName = FndDAL.SQLite;
                string where = "pres_object = '" + objSec.pres_object + "' and sec_object = '" + objSec.sec_object + "'";
                int suc = 0;
                if (fnd_object_security.Find(where) != null)
                    suc = objSec.Update();
                else
                    suc = objSec.Insert();
                fnd_object_security.Meta.ConnName = conName;
                if (suc == 1)
                    return true;
                else
                    return false;
            }
            else
            {
                SalString sSql = "SecuritySys_NewPresSecurity(:pres_object_,:sec_object_,:sec_object_type_,:sub_object_type_,:force_read_only_,:description_)";
                SalBoolean res = true;
                if (cSessionManager.IsRemote)
                {
                    res = cSessionManager.RemoteSQLExecute(objSec, sSql);
                    if (res)
                        ObjectSecuritys.Add(objSec);
                }
                else
                {
                    cSessionManager session = new cSessionManager(null);
                    session.DbTransactionBegin(objSec);
                    res = session.DbSQLBlock(objSec, sSql, false);
                    if (res)
                    {
                        session.DbTransactionEnd(objSec);
                        ObjectSecuritys.Add(objSec);
                    }
                    else
                        session.DbTransactionClear(objSec);
                }
                return res;
            }
        }
        public static void AddObjectSecurityToDb()
        {
            if (!AppEnvironment.Session.IsRoot)
                return;
            string conName = fnd_object_security.Meta.ConnName;
            fnd_object_security.Meta.ConnName = FndDAL.SQLite;

            List<fnd_object_security> list = fnd_object_security.FindAll();
            fnd_object_security.Meta.BeginTrans();
            fnd_object_security.Meta.Execute("delete from fnd_object_security_tab");
            fnd_object_security.Meta.Commit();

            fnd_object_security.Meta.ConnName = conName;

            foreach (fnd_object_security secObj in list)
            {
                ObjectSecurityNew(secObj, false);
            }
        }
        public static void AddPresObjectToDb()
        {
            if (!AppEnvironment.Session.IsRoot)
                return;
            string conName = fnd_pres_object.Meta.ConnName;
            fnd_pres_object.Meta.ConnName = FndDAL.SQLite;

            List<fnd_pres_object> list = fnd_pres_object.FindAll();
            fnd_pres_object.Meta.BeginTrans();
            fnd_pres_object.Meta.Execute("delete from fnd_pres_object_tab");
            fnd_pres_object.Meta.Commit();

            fnd_pres_object.Meta.ConnName = conName;

            foreach (fnd_pres_object secObj in list)
            {
                PresObjectNew(secObj, false);
            }
        }
        public static void AddDSSecurity(Type t,string secObject, string subType, string desc, string forceRd)
        {
            if (!AppEnvironment.Session.IsRoot)
                return;
            
            fnd_object_security objSec = FndObjectFactory.CreateObjectSecurity(t, secObject, SecObjectType.Database, subType, desc, forceRd);
            
            if (FndDAL.FindObjectSecurity(objSec) == null)
            {
                FndDAL.ObjectSecurityNew(objSec);
            }
        }

        //public static SalBoolean FndBinaryObjectModify(fnd_binary_object binObject)
        //{
        //    if (binObject == null)
        //        return false;
        //    cSessionManager session = new cSessionManager(null);
        //    session.DbTransactionBegin(binObject);
        //    SalString sSql = "FndBinaryObject_ModifyObject(:blob_id_,:file_path_,:file_name_,:display_text_,:data_)";
        //    SalBoolean res = session.DbSQLBlock(binObject, sSql, false);
        //    if (res)
        //    {
        //        session.DbTransactionEnd(binObject);
                
        //    }
        //    else
        //        session.DbTransactionClear(binObject);
        //    return res;
        //}
        //public static SalBoolean FndBinaryObjectNew(fnd_binary_object binObject)
        //{
        //    if (binObject == null)
        //        return false;
        //    cSessionManager session = new cSessionManager(null);
        //    session.DbTransactionBegin(binObject);
        //    SalString sSql = "FndBinaryObject_NewObject(:blob_id_,:file_path_,:file_name_,:display_text_,:data_)";
        //    SalBoolean res = session.DbSQLBlock(binObject, sSql, false);
        //    if (res)
        //    {
        //        session.DbTransactionEnd(binObject);

        //    }
        //    else
        //        session.DbTransactionClear(binObject);
        //    return res;
        //}

        //public static SalBoolean FndBinaryObjectRemove(fnd_binary_object binObject)
        //{
        //    if (binObject == null)
        //        return false;
        //    cSessionManager session = new cSessionManager(null);
        //    session.DbTransactionBegin(binObject);
        //    SalString sSql = "FndBinaryObject_RemoveObject(:blob_id_)";
        //    SalBoolean res = session.DbSQLBlock(binObject, sSql, false);
        //    if (res)
        //    {
        //        session.DbTransactionEnd(binObject);

        //    }
        //    else
        //        session.DbTransactionClear(binObject);
        //    return res;
        //}
        //public static fnd_language_sys FindLanguageObject(fnd_language_sys langObj)
        //{

        //}
    }
}
